package cn.example.vip.mall.api.hot;

import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 热门商品排队
 * 1.Redis存储热门商品
 * 2.RocketMQ排队并转发
 */
@Component
public class HotQueue {
	
	// 商品非热门
	public static final	Integer NOT_HOT = 0;
	// 已在排队中
	public static final	Integer HAS_QUEUE = 204;
	// 排队成功
	public static final Integer QUEUE_ING = 200;
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private RocketMQTemplate rocketMQTemplate;
	
	/**
	 * 抢单排队
	 * @param username
	 * @param id
	 * @param num
	 */
	public Integer hotToQueue(String username, String id, Integer num){
		// 1.获取该商品在Redis中的信息(热门商品),(恶意抢单判定),(DOS攻击判定)
		Boolean flag = redisTemplate.boundHashOps("HotSeckillGoods").hasKey(id);
		if(!flag){
			return NOT_HOT;
		}
		// 2.多次请求合并，避免重复排队
		Long increment = redisTemplate.boundValueOps("OrderQueue").increment(1);
		if(increment > 1){
			// 请勿重复排队
			return HAS_QUEUE;
		}
		
		// 3.执行排队操作
		Map<String, Object> dataMap = new HashMap<>();
		dataMap.put("username", username);
		dataMap.put("id", id);
		dataMap.put("num", num);
		
		Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(dataMap)).build();
		rocketMQTemplate.convertAndSend("order-queue", message);
		return QUEUE_ING;
	}
}
